<template>
  <el-card
    shadow="never"
    :body-style="{ padding: '0px' }"
    :page-size="pageSize"
    :total="rows"
    :current-page="pageNo"
    @current-change="currentChangeHandle"
  >
    <el-form class="p-4" inline :model="dataForm">
      <el-form-item>
        <el-input
          v-model="dataForm.operatorName"
          maxlength="32"
          :placeholder="$t('operator.name')"
          clearable
          @blur="() => (dataForm.operatorName = dataForm.operatorName.trim())"
          @keyup.enter.native="getDataList((pageNo = 1))"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="selectDate"
          type="month"
          value-format="YYYY-MM"
          format="YYYY-MM"
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          class="w-8"
          @click="getDataList((pageNo = 1))"
        >
          <svg-icon icon-class="search" />
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="isAuth('10402002.MANAGE')"
          type="primary"
          class="w-8"
          @click="openRegeneratePush"
        >
          <svg-icon icon-class="Upload" />
        </el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="dataListLoading" :data="dataList" stripe>
      <el-table-column prop="characterName" :label="$t('operator.name')" />
      <el-table-column prop="linkMan" :label="$t('operator.linkman')" />
      <el-table-column
        prop="countryCode"
        :formatter="formatCountry"
        :label="$t('operator.country')"
      />
      <el-table-column
        prop="levelCode"
        :label="$t('operator.level')"
      >
        <template v-slot="scope">
          <el-tag
            v-if="
              scope.row.levelCode === 'STANDARD_LEVEL' ||
              scope.row.levelCode === 'ENTERPRISE_LEVEL'
            "
            size="small"
          >
            {{
              expirationHandler(scope.row.levelCode, scope.row.levelExpireTime)
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        :label="$t('statistic.statistic_recode_status')"
      >
        <template v-slot="scope">
          {{ $t('statistic.statistic_recode_status_list.' + scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column width="75px">
        <template v-slot="scope">
          <div :title="$t('common.detail')">
            <el-button text class="w-8" @click="showDetailHandle(scope.row)">
              <svg-icon icon-class="View" />
            </el-button>
          </div>
          <!-- <el-dropdown class="align-middle" trigger="click">
            <el-button text class="w-8">
              <svg-icon icon-class="MoreFilled" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showDetailHandle(scope.row)">
                  <svg-icon icon-class="View" />
                  {{ $t("common.detail") }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown> -->
          <!-- <el-tooltip
            class="item"
            effect="dark"
            :content="$t('common.detail')"
            placement="top"
          >
            <el-button
              type="text"
              style="color: #8c939d"
              icon="el-icon-view"
              @click="showDetailHandle(scope.row)"
            />
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <regenerate-push ref="regeneratePush" v-model="regenerateVisible" />
  </el-card>
</template>
<script>
import { formatDate } from '@/utils/formatDate'
import { timeFilter, dateFilter } from '@/filters/index'
import { formatCountry } from '@/utils/formatCountry'
import {
  getCharacterList,
  regenerateStatisticData,
  rePushStatisticData
} from '@/api/statistic-operator'
import RegeneratePush from '@/views/platform-report/component/regenerate-push'
import { isAuth } from '@/utils'

export default {
  components: {
    RegeneratePush
  },
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      yearList: [],
      monthList: [],
      selectDate: '',
      regenerateVisible: false,
      dataForm: {
        operatorName: ''
      },
      dataList: [],
      rows: 0,
      dataListLoading: false,
      platCode: 'TOMS',
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getFullYear() * 100 + time.getMonth() >
            new Date().getFullYear() * 100 + new Date().getMonth()
          )
        }
      }
    }
  },
  computed: {},
  mounted() {
    this.getSelectDate()
    this.getDataList()
  },
  methods: {
    isAuth,
    timeFilter,
    dateFilter,
    getSelectDate() {
      const date = new Date()
      const currentYear = date.getFullYear() + ''
      const currentMonth = date.getMonth() + 1
      const month = date.getMonth() >= 10 ? currentMonth : '0' + currentMonth
      this.selectDate = currentYear + '-' + month
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val
      this.getDataList()
    },
    // 获取数据列表
    getDataList() {
      if (!this.selectDate) {
        this.getSelectDate()
      }
      this.dataListLoading = true
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        characterName: this.dataForm.operatorName,
        platCode: this.platCode,
        characterCode: 'OPERATOR',
        statYear: Number(this.selectDate.split('-')[0]),
        statMonth: Number(this.selectDate.split('-')[1])
      }
      console.log(this.selectDate)
      getCharacterList(params)
        .then((data) => {
          this.dataList = data.list
          this.rows = data.total
          this.dataListLoading = false
        })
        .catch((e) => {
          this.dataListLoading = false
          this.$message.error(e.message)
        })
    },
    showDetailHandle(row) {
      this.$store.commit('app/ADD_KEEP_ALIVE_LIST', 'StatisticOperator')
      this.$router.push({
        path: `/platform-report/operator-detail`,
        query: {
          platCode: this.activeTab,
          operatorId: row.keyId,
          operatorName: row.characterName,
          year: Number(this.selectDate.split('-')[0]),
          month: Number(this.selectDate.split('-')[1])
        }
      })
    },
    regenerateStatisticData() {
      this.$confirm(this.$t('statistic.regenarate_repush_confirm'), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        const keyIds = []
        this.selectedData.forEach((item) => {
          keyIds.push(item.keyId)
        })
        var data = {
          year: Number(this.selectDate.split('-')[0]),
          month: Number(this.selectDate.split('-')[1]),
          keyIds: keyIds,
          characterCode: 'OPERATOR'
        }
        regenerateStatisticData(data)
          .then(() => {
            this.$message.success(this.$t('statistic.success'))
          })
          .catch((e) => {
            this.$message.error(e.message)
          })
      })
    },
    rePushStatisticData() {
      const keyIds = []
      this.selectedData.forEach((item) => {
        keyIds.push(item.keyId)
      })
      var data = {
        year: Number(this.selectDate.split('-')[0]),
        month: Number(this.selectDate.split('-')[1]),
        keyIds: keyIds,
        characterCode: 'OPERATOR'
      }
      rePushStatisticData(data)
        .then(() => {
          this.$message.success(this.$t('statistic.success'))
        })
        .catch((e) => {
          this.$message.error(e.message)
        })
    },
    openRegeneratePush() {
      this.regenerateVisible = true
      this.$nextTick(() => {
        this.$refs.regeneratePush.openDialog('TOMS')
      })
    },
    formatDate(cellValue, fmt) {
      cellValue = new Date(cellValue).valueOf()
      return formatDate(cellValue, fmt)
    },
    formatCountry(row, column, cellValue, index) {
      return formatCountry(cellValue)
    },
    expirationHandler(levelCode, levelExpirationTime) {
      // eslint-disable-next-line no-unused-vars
      let levelName = ''
      if (levelCode === 'STANDARD_LEVEL') {
        // levelName = this.$t('operator.level_list[0].label')
        levelName = 'L1'
      } else if (levelCode === 'ENTERPRISE_LEVEL') {
        // levelName = this.$t('operator.level_list[1].label')
        levelName = 'L2'
      }
      if (!levelExpirationTime || levelExpirationTime === undefined) {
        return levelName + ' | ' + this.$t('operator.leverExpireForever')
      }
      var date = formatDate(levelExpirationTime, 'YYYY-MM-DD')
      return levelName + ' | ' + date
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      let value = row[column.property]
      if (value != null) {
        if (column.property === 'creTime') {
          value = this.formatDate(row[column.property], 'YYYY-MM-DD')
        }
        if (column.property === 'countryCode') {
          value = formatCountry(row[column.property])
        }
        if (value.length * 13 > column.width) {
          return 'font-size:' + (column.width * 0.95) / value.length + 'px'
        }
      }
    }
  }
}
</script>
